﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using HCQ2_Common.Log;
using NPOI.OpenXml4Net.OPC.Internal;

namespace HCQ2_Common
{
    /// <summary>
    ///  request帮助类
    /// </summary>
    public class RequestHelper
    {
        /// <summary>
        ///  获取Request对象
        /// </summary>
        public static HttpRequest Request
        {
            get { return HttpContext.Current.Request; }
        }

        /// <summary>
        ///  获取cookie
        /// </summary>
        /// <param name="cookieName"></param>
        /// <returns></returns>
        public static string GetCookie(string cookieName)
        {
            var cookie = Request.Cookies[cookieName];
            if (cookie != null)
                return cookie.Value;
            return string.Empty;
        }

        /// <summary>
        ///  获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string GetIP
        {
            get
            {
                string iP = string.Empty;
                if (!string.IsNullOrEmpty(Request.ServerVariables["HTTP_VIA"]))
                    iP = Convert.ToString(Request.ServerVariables["HTTP_X_FORWARDED_FOR"]);
                if (string.IsNullOrEmpty(iP))
                    iP = Convert.ToString(Request.ServerVariables["REMOTE_ADDR"]);
                return iP;
            }
        }

        /// <summary>
        ///  获取浏览器
        /// </summary>
        /// <returns></returns>
        public static string GetBrowser
        {
            get
            {
                return Request.Browser.Browser;
            }
        }

        /// <summary>
        ///  浏览器版本
        /// </summary>
        /// <returns></returns>
        public static string GetBroMaVersion
        {
            get
            {
                return Request.Browser.MajorVersion.ToString();
            }
        }

        /// <summary>
        ///  获取操作系统
        /// </summary>
        /// <returns></returns>
        public static string GetPlatform
        {
            get
            {
                return Request.Browser.Platform;
            }
        }

        /// <summary>
        ///  获取请求地址
        /// </summary>
        /// <returns></returns>
        public static string GetUrl
        {
            get
            {
                return Request.Url.ToString();
            }
        }

        /// <summary>
        ///  通过request获取string
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetStrByName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return null;
            return Helper.ToString(Request[name]);
        }

        /// <summary>
        ///  通过request获取string
        ///  需要解码
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetDeStrByName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return null;
            return HttpUtility.UrlDecode(Helper.ToString(Request[name]));
        }

        /// <summary>
        ///  通过request获取int
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static int GetIntByName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return 0;
            string str = Request[name];
            if (string.IsNullOrEmpty(str))
                return 0;
            return Helper.ToInt(str);
        }

        /// <summary>
        ///  通过request获取decimal
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static decimal GetDecimalByName(string name)
        {
            if (string.IsNullOrEmpty(name))
                return 0;
            string str = Request[name];
            if (string.IsNullOrEmpty(str))
                return 0;
            return Helper.ToDecimal(str);
        }
        /// <summary>
        /// 发送get请求获取响应的数据
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string SendGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "textml;charset=UTF-8";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream myResponseStream = response.GetResponseStream();
            StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
            string jsonData = myStreamReader.ReadToEnd();
            myStreamReader.Close();
            myResponseStream.Close();

            return jsonData;
        }

        /// <summary>
        /// 发送post请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="data">参数数据</param>
        /// <param name="contentType">contentType默认值：application/json;charset=UTF-8</param>
        /// <returns></returns>
        public static string SendPost(string url,object data,string contentType = "application/json;charset=UTF-8")
        {
            string datastr = JsonHelper.ObjectToJson(data);
            LogHelper.InfoLog(typeof(RequestHelper), $"调用接口地址：{url}，调用的参数：{datastr}");

            byte[] sendData = Encoding.UTF8.GetBytes(datastr);

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "POST";
            request.ContentType = contentType;
            request.ContentLength = sendData.Length;

            using (Stream streamRequest = request.GetRequestStream())
            {
                //写入请求数据
                streamRequest.Write(sendData, 0, sendData.Length);
                streamRequest.Close();

                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                }
                catch (WebException w)
                {
                    //如果有500错误这些，返回相关的内容
                    response = (HttpWebResponse)w.Response;
                }
                //获取返回数据
                using (Stream myResponseStream = response.GetResponseStream())
                {
                    StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.UTF8);
                    string jsonData = myStreamReader.ReadToEnd();
                    return jsonData;
                }
                
            }            
        }

        /// <summary>
        /// Post Http请求
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="postData">数据</param>
        /// <param name="timeout">请求超时时间毫秒默认：5000</param>
        /// <param name="contentType"></param>
        /// <param name="encode">编码，默认：UTF-8</param>
        /// <returns>响应流字符串</returns>
        public static string SendPost(string url, int timeout = 5000, string postData = "", string contentType = "application/json;", string encode = "UTF-8")
        {
            //LogHelper.InfoLog("发送HTTP POST请求");
            //LogHelper.InfoLog($"URL:{url}");
            //LogHelper.InfoLog($"请求数据：{postData}");

            //return "{\"ReturnStatus\":\"Success\",\"Message\":\"ok\",\"RemainPoint\":13947,\"TaskID\":113957764,\"SuccessCounts\":170} ";

            if (!string.IsNullOrEmpty(url) && !string.IsNullOrEmpty(encode) && !string.IsNullOrEmpty(contentType) && postData != null)
            {
                HttpWebResponse webResponse = null;
                Stream responseStream = null;
                Stream requestStream = null;
                StreamReader streamReader = null;
                try
                {

                    return GetStreamReader(url, responseStream, requestStream, streamReader, webResponse, timeout, encode, postData, contentType);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    if (responseStream != null) responseStream.Dispose();
                    if (webResponse != null) webResponse.Dispose();
                    if (requestStream != null) requestStream.Dispose();
                    if (streamReader != null) streamReader.Dispose();
                }
            }
            return null;
        }

        /// <summary>
        /// 发送post请求，返回直接类型结果
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="data">参数数据</param>
        /// <param name="contentType">contentType默认值：application/json;charset=UTF-8</param>
        /// <returns></returns>
        public static T SendPost<T>(string url, string data, string contentType = "application/json;charset=UTF-8")
        {
            string r = SendPost(url,data,contentType);
            if (string.IsNullOrEmpty(r)) {
                return default(T);
            }
            return JsonHelper.JsonStrToObject<T>(r);
        }

        /// <summary>
        /// 获取API请求时根地址
        /// </summary>
        /// <returns></returns>
        public static string GetApiRequestRootUrl() {
            return HttpContext.Current.Request.Url.AbsoluteUri.Substring(0, HttpContext.Current.Request.Url.AbsoluteUri.IndexOf("/api/"));
        }

        private static string GetStreamReader(string url, Stream responseStream, Stream requestStream, StreamReader streamReader, WebResponse webResponse, int timeout, string encode, string postData, string contentType)
        {
            byte[] data = Encoding.GetEncoding(encode).GetBytes(postData);
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.ContentType = contentType + ";" + encode;
            webRequest.ContentLength = data.Length;
            webRequest.Timeout = timeout;
            requestStream = webRequest.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            webResponse = (HttpWebResponse)webRequest.GetResponse();
            responseStream = webResponse.GetResponseStream();
            if (responseStream == null) { return ""; }
            streamReader = new StreamReader(responseStream, Encoding.GetEncoding(encode));
            return streamReader.ReadToEnd();
        }
    }
}
